package com.alphagen.sample.bestroute;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class GetRouteFromGoogle {

	private String sourcePlace;
	private String destPlace;
	
	public String getSourcePlace() {
		return sourcePlace;
	}
	public void setSourcePlace(String sourcePlace) {
		this.sourcePlace = sourcePlace;
	}
	public String getDestPlace() {
		return destPlace;
	}
	public void setDestPlace(String destPlace) {
		this.destPlace = destPlace;
	}	
	
	public JSONArray queryGoogle() throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		JSONArray routeJSON = null;
		HttpGet httpGet = new HttpGet(
				"https://maps.googleapis.com/maps/api/directions/json?origin="+getSourcePlace()+"&destination="+getDestPlace()+"&sensor=false");
		httpGet.getHeaders("");
		CloseableHttpResponse response1 = httpclient.execute(httpGet);

		try {
			System.out.println(response1.getStatusLine());
			HttpEntity entity1 = response1.getEntity();

			String strResponse = EntityUtils.toString(entity1);
			JSONObject jsonObj = new JSONObject(strResponse);

			routeJSON = jsonObj.getJSONArray("routes");

			EntityUtils.consume(entity1);
		} finally {
			response1.close();
		}

		return routeJSON;
	}
}
